package com.ali.ttt.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @Author : yuxl
 * @create 2024/8/1 2:57 PM
 */
@Slf4j
@RestController
@RequestMapping("/api/waitingNotification")
@Api(tags = "等待通知")
@AllArgsConstructor
public class WaitingNotificationController {

    private static final Object OBJ = new Object();

    @GetMapping("/wait")
    @ApiOperation(value = "等待")
    public void waitThread() throws InterruptedException {
        Thread t = new Thread(() -> {
            try {
                log.info("wait 开始执行");
                synchronized (OBJ) {
                    // wait 会释放锁
                    OBJ.wait();
                }
                log.info("wait 结束");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "wait");
        t.start();
    }

    @GetMapping("/notify")
    @ApiOperation(value = "唤醒")
    public void notifyThread() {
        synchronized (OBJ) {
            OBJ.notifyAll();
        }
    }

    private static Thread t;


    @GetMapping("/park")
    @ApiOperation(value = "park")
    public void park() {
        t = new Thread(() -> {
            log.info("park 开始执行");
            LockSupport.park();
            log.info("park 结束");

        }, "park");
        t.start();
    }

    @GetMapping("/unpark")
    @ApiOperation(value = "unpark")
    public void unpark() {
        LockSupport.unpark(t);
    }
}
